package io.geekidea.boot.area.controller;


import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.geekidea.boot.Import.ExcelListener;
import io.geekidea.boot.area.dto.AreaDto;
import io.geekidea.boot.area.entity.Area;

import io.geekidea.boot.area.entity.ExcelArea;
import io.geekidea.boot.area.entity.ImportArea;
import io.geekidea.boot.area.mapper.ExcelAreaMapper;
import io.geekidea.boot.area.query.AreaQuery;
import io.geekidea.boot.area.service.AreaService;

import io.geekidea.boot.area.service.ExcelAreaService;
import io.geekidea.boot.common.PageDto;
import io.geekidea.boot.framework.response.ApiResult;
import io.geekidea.boot.warehousentry.dto.WarehousentryExcel;
import io.geekidea.boot.warehousentry.query.WarehousentryQuery;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.math3.ml.neuralnet.UpdateAction;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/area")
@Tag(name="战区管理")
public class AreaController {
    @Resource
    private AreaService areaService;

    @Autowired
    private ExcelAreaMapper excelMapper;

    @PostMapping("/search")
    @Operation(summary = "搜索战区",description = "按照多条件组合分页查询战区数据列表")
    public ApiResult search(@RequestBody AreaQuery areaQuery){
        Page<Area> page=new Page<>(areaQuery.getPage(),areaQuery.getSize());
        LambdaQueryWrapper<Area> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(StringUtils.isNotBlank(areaQuery.getAreaName()),Area::getName,areaQuery.getAreaName());
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(areaQuery.getAreaCode()),Area::getCode,areaQuery.getAreaCode());
        Page<Area> pageDto=areaService.page(page,lambdaQueryWrapper);
        PageDto<Area> pageInfo=new PageDto<>(pageDto.getRecords(),pageDto.getTotal(),pageDto.getSize(),pageDto.getCurrent());
        return ApiResult.success(pageInfo);
    }

    @PostMapping("/import")
    public ApiResult myImport(@RequestPart MultipartFile file) {
        try {
            //获取文件名
            String filename = file.getOriginalFilename();
            System.out.println(filename);
            if (filename==null||filename==""){
                return ApiResult.error("file不存在");
            }
            //获取文件流
            InputStream inputStream = file.getInputStream();
            //实例化实现了AnalysisEventListener接口的类
            ExcelListener listener = new ExcelListener();

            EasyExcelFactory.read(inputStream, ExcelArea.class, listener).headRowNumber(1).build().readAll();
            //获取数据
            List<Object> list = listener.getDatas();
            if (list.size() > 1) {
                for (int i = 0; i < list.size(); i++) {
                    ExcelArea excel = (ExcelArea) list.get(i);
                    System.out.println(excel.toString());
                    //使用mybatis-plus添加到数据库
                    excelMapper.insert(excel);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResult.error("导入失败，请检查是否有相同战区或文件格式");
        }

        return ApiResult.success("导入成功",200);
    }


    @PostMapping("/download")
    public void download(AreaQuery areaQuery, HttpServletResponse response){
        //WarehousentryQuery warehousentryQuery = new WarehousentryQuery();

        List<ImportArea> list = areaService.getDownloadAreaList(areaQuery);

        OutputStream outputStream = null;
        try {
            response.setCharacterEncoding("UTF-8");
            String excelName = URLEncoder.encode("warehousentry_"+ LocalDateTime.now(), "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + excelName + ".xlsx");
            // 以字节流的形式输出响应正文
            outputStream = response.getOutputStream();
            try (ExcelWriter excelWriter = EasyExcel.write(outputStream, ImportArea.class).build()) {
                WriteSheet writeSheet = EasyExcel.writerSheet(0).build();
                excelWriter.write(list,writeSheet);
            }
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }
        }
    }

    @GetMapping("/get/{id}")
    @Operation(summary = "根据ID查询单条数据")
    public ApiResult getAreaById(@PathVariable(value = "id")Integer id){
        final  Area area=areaService.getById(id);
        return ApiResult.success(area);
    }

    @DeleteMapping("/romove/{id}")
    @Operation(summary = "逻辑删除战区")
    public ApiResult removeArea(@PathVariable(value = "id")Integer id){
        areaService.removeById(id);
        return ApiResult.success("删除战区数据成功！");
    }

    @PostMapping("/add")
    public ApiResult addArea(@RequestBody AreaDto areaDto){
        Area areaEntity=new Area();
        BeanUtil.copyProperties(areaDto,areaEntity);
        areaService.save(areaEntity);
        return ApiResult.success("添加战区数据成功！");
    }

    //逻辑删除
    @GetMapping("/del/{id}")
    @Operation(summary = "物理删除",description = "根据id逻辑删除对应的列")
    public ApiResult del(@PathVariable Integer id){
        boolean update = areaService.delById(id);
        if (!update) {
            return ApiResult.success("删除失败");
        }
        return ApiResult.success("删除成功");

    }


    @PostMapping("/update")
    public ApiResult updateArea(@Validated(value = {UpdateAction.class})@RequestBody AreaDto areaDto){
        Area areaEntity=new Area();
        BeanUtil.copyProperties(areaDto,areaEntity);
        areaService.updateById(areaEntity);
        return ApiResult.success("更改战区数据成功！");
    }


    @PostMapping("/list")
    @Operation(summary = "查询战区所有基础数据")
    public ApiResult areaList(@RequestBody AreaQuery areaQuery){
        LambdaQueryWrapper<Area> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(StringUtils.isNotBlank("0"),Area::getStatus,"0");
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(areaQuery.getId()),Area::getId,areaQuery.getId());
        List<Area> areaList = areaService.list(lambdaQueryWrapper);
        return ApiResult.success(areaList);
    }
}
